/**
 * Copyright © 2018 TaoYu (tracy5546@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.baomidou.kaptcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.time.Instant;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_DATE;
import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * 谷歌默认验证码组件
 *
 * @author TaoYu
 */
@Slf4j public class GoogleKaptcha implements Kaptcha {

    private DefaultKaptcha kaptcha;

    public GoogleKaptcha(DefaultKaptcha kaptcha) {
        this.kaptcha = kaptcha;
    }

    @Override public Mono<ServerResponse> render(ServerRequest request) {
        String text = kaptcha.createText();
        request.session().subscribe(webSession -> {
            webSession.getAttributes().put(KAPTCHA_SESSION_KEY, text);
            webSession.getAttributes().put(KAPTCHA_SESSION_DATE, Instant.now());
        });
        DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
        DataBuffer dataBuffer = factory.allocateBuffer();
        Flux<DataBuffer> dataBufferFlux = Flux.just(dataBuffer);

        return ServerResponse.ok().header(HttpHeaders.EXPIRES, "0")
            .header(HttpHeaders.CACHE_CONTROL, "no-store, no-cache, must-revalidate")
            .header(HttpHeaders.CACHE_CONTROL, "post-check=0, pre-check=0")
            .header(HttpHeaders.PRAGMA, "no-cache").contentType(MediaType.IMAGE_JPEG)
            .body(BodyInserters.fromDataBuffers(dataBufferFlux.doOnNext(df -> {
                try {
                    ImageIO.write(kaptcha.createImage(text), "jpg", df.asOutputStream());
                } catch (IOException e) {
                    log.error("kaptcha", e);
                }
            })));
    }

}
